package jee.boot.data.permission.execute;

import jee.boot.common.basic.DataEntity;
import jee.boot.common.basic.ServiceException;
import jee.boot.common.basic.interceptor.PreUpdateInterceptor;
import jee.boot.common.utils.JeeBootContext;
import jee.boot.common.utils.StringUtils;
import jee.boot.data.permission.config.AuthInterceptorThreadContext;
import jee.boot.entity.auth.AuthConstant;
import jee.boot.entity.auth.AuthEntity;
import jee.boot.entity.auth.OperationLevel;
import jee.boot.entity.auth.StandardModel;
import jee.boot.entity.auth.User;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 对更新的请求进行拦截,设置权限规则
 */
public class PreUpdateExecuteInterceptor extends BasicExecute implements PreUpdateInterceptor {
    /**
     * 执行前置操作
     *
     * @param entity
     */
    @Override
    public void execute(DataEntity<?> entity) {
        if (!AuthInterceptorThreadContext.isAuthPermission()) {
            return;
        }
        User currentUser = getCurrentUser();
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        String uri;
        if (httpServletRequest != null) {
            uri = httpServletRequest.getRequestURI();
        } else {
            uri = JeeBootContext.get(JeeBootContext.REFERER_URI);
        }
        // 如果没有request,并且没有设置上下文的环境变量,不做拦截
        if (StringUtils.isBlank(uri)) {
            return;
        }
        // 没有授权用户的不拦截
        if (currentUser == null) {
            return;
        }
        Map<String,Object> data=null;
        // 模型的数据权限拦截
        if (StandardModel.class.equals(entity.getClass())) {
            StandardModel standardModel = (StandardModel) entity;
            standardModel.data2db();
//            List<AuthEntity> rowSetList = mergeRowSetPermission(currentUser.getRowSetList(), uri);
            // 配置rowSet权限
            configRowSetPermission(currentUser, standardModel);
            // 配置CellSet权限
            configCellSetPermission(currentUser, standardModel);
            data=standardModel.getDb();
        }
        if(data==null){
            data=dataEntity2Map(entity);
        }
        // 标准数据权限拦截
        List<AuthEntity> rowSetPermission = getCurrentRequestRowSetPermission(currentUser, entity);
        if (rowSetPermission != null && !rowSetPermission.isEmpty()) {
            // 这里先忽略cell的设置吧,将来的将来有需要在加上
            AuthEntity defaultVisible = new AuthEntity(new OperationLevel(0, AuthConstant.OPERATION_LEVEL_EDITABLE));
            AuthEntity authEntityInRowSet = rowDataInRowSetPermission(data, rowSetPermission,defaultVisible);
            if(!StringUtils.equals(AuthConstant.OPERATION_LEVEL_EDITABLE,authEntityInRowSet.getOperationLevel().getRuleKeyword())){
                throw new ServiceException(1206);
            }
        }

    }
}
